<template>
  <div class="table-box">
    <ProTable ref="proTable" title="工序列表" :columns="columns" :data="processList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="openDrawerStatic('新增')">新增工序</el-button>
        <el-button type="danger" :icon="Delete" plain @click="batchDelete(scope.selectedListIds)" :disabled="!scope.isSelected">
          批量删除工序
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawerStatic('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawerStatic('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <ProcessDrawer ref="drawerRef" @refresh="fetchProcessList" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, onMounted } from "vue";
import { Process } from "@/api/interface";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import axios from "axios";
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import ProcessDrawer from "@/views/proTable/components/ProcessDrawer.vue";
import { ElMessageBox, ElMessage } from "element-plus";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 表格配置项
const columns: ColumnProps<Process.ResProcess>[] = [
  { type: "selection", fixed: "left", width: 80 },
  {
    prop: "processId",
    label: "工序编号",
    search: { el: "input" }
  },
  {
    prop: "processName",
    label: "工序名称",
    search: { el: "input" }
  },
  {
    prop: "description",
    label: "工序描述"
  },
  {
    prop: "createTime",
    label: "创建时间",
    width: 180,
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" },
      defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"]
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
];

// 基础 URL
const baseUrl = import.meta.env.VITE_BASE_URL;

// 工序列表数据
const processList = ref<Process.ResProcess[]>([]);

// 获取全部工序数据（包含设备信息）
const fetchProcessList = async () => {
  try {
    const res = await axios.get(`${baseUrl}/api/carbon/getAllProcesses`);
    if (res.data.code === 200) {
      // 后端统一返回结构为 { data: any }
      processList.value = res.data.data ?? [];
      console.log("从后端获取工序列表 ", processList.value);
    } else {
      ElMessage.error(res.data.msg || "获取工序列表失败");
      return [];
    }
  } catch (error) {
    console.error(error);
    ElMessage.warning("获取工序列表失败");
  }
};

// 组件挂载时拉取数据
onMounted(() => {
  fetchProcessList();
});

// 删除单条工序
const deleteAccount = async (row: Process.ResProcess) => {
  ElMessageBox.confirm("是否删除该项?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      try {
        const resp = await axios.post(`${baseUrl}/api/carbon/deleteProcess`, { id: row.id });
        if (resp.data && resp.data.code === 200) {
          ElMessage.success("删除工序成功!");
          fetchProcessList(); // 重新获取列表
        } else {
          ElMessage.error(resp.data.msg || "删除工序失败");
        }
      } catch (error: any) {
        const msg = error?.response?.data?.msg || "删除工序失败，请稍后重试";
        ElMessage.error(msg);
      }
    })
    .catch(() => {});
};

const batchDelete = async (ids: string[]) => {
  ElMessageBox.confirm("是否删除所选项?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      try {
        // 调用后端批量删除接口
        const resp = await axios.post(`${baseUrl}/api/carbon/batchDeleteProcesses`, { ids });
        if (resp.data && resp.data.code === 200) {
          ElMessage.success("批量删除工序成功!");
          // 刷新表格数据
          fetchProcessList();
          // 清空选择
          proTable.value?.clearSelection();
        } else {
          ElMessage.error(resp.data.msg || "批量删除工序失败");
        }
      } catch (error: any) {
        const msg = error?.response?.data?.msg || "批量删除工序失败，请稍后重试";
        ElMessage.error(msg);
      }
    })
    .catch(() => {});
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof ProcessDrawer> | null>(null);
// 静态方法（操作静态数组）
const openDrawerStatic = (title: string, row: Partial<Process.ResProcess> = {}) => {
  // 定义静态操作
  const params = {
    title,
    isView: title === "查看",
    row: { ...row } // 静态模式下仅操作此行数据
  };
  drawerRef.value?.acceptParams(params);
};
</script>
